package org.liaohailong.library.widget.interact

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import org.liaohailong.library.widget.interact.audio.InteractAudioView
import org.liaohailong.library.widget.interact.image.InteractImageView
import org.liaohailong.library.widget.interact.text.InteractTextView
import org.liaohailong.library.widget.interact.video.InteractVideoView

/**
 * Author: liaohailong
 * Date: 2019/3/13
 * Time: 9:40 AM
 * Description: 互动插件父容器
 **/
class InteractContainer(context: Context, attributeSet: AttributeSet?, defStyle: Int) : FrameLayout(context, attributeSet, defStyle) {

    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
    constructor(context: Context) : this(context, null)

    fun setMessage(message: Message, callback: IInteractView.InteractViewCallback) {
        hideAll()

        var view = findViewByType(message.type)
        if (view == null) {
            if (add(message.type)) {
                view = findViewByType(message.type)
            }
        }

        view?.apply {
            if (view is View) show(view)
            play(message, callback)
        }
    }

    private fun hideAll() {
        for (i in 0 until childCount) {
            val view = getChildAt(i)
            view.visibility = View.GONE
        }
    }

    private fun findViewByType(type: Message.Type): IInteractView? {
        val interactView: Class<out IInteractView> = when (type) {
            Message.Type.TEXT -> InteractTextView::class.java
            Message.Type.IMAGE -> InteractImageView::class.java
            Message.Type.AUDIO -> InteractAudioView::class.java
            Message.Type.VIDEO -> InteractVideoView::class.java
        }
        for (i in 0 until childCount) {
            val view = getChildAt(i)
            if (interactView.isAssignableFrom(view.javaClass)) {
                return view as IInteractView
            }
        }
        return null
    }

    private fun add(type: Message.Type): Boolean {
        val interactView: IInteractView = when (type) {
            Message.Type.TEXT -> InteractTextView(context)
            Message.Type.IMAGE -> InteractImageView(context)
            Message.Type.AUDIO -> InteractAudioView(context)
            Message.Type.VIDEO -> InteractVideoView(context)
        }
        if (interactView is View) {
            interactView.visibility = View.GONE
            addView(interactView)
            return true
        }
        return false
    }

    private fun show(view: View) {
        view.visibility = View.VISIBLE
        bringChildToFront(view)
    }
}